package com.ja.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.web.context.ContextLoader;

import com.ja.domain.KeFuChat;
import com.ja.sevice.KeFuService;
/**
 * 会话连接-关闭-消息传递
 * @author Administrator
 *2018年9月19日
 *
 */
@ServerEndpoint("/websocket")
public class ChatController2{
	
	private KeFuService keFuService = (KeFuService) ContextLoader.getCurrentWebApplicationContext().getBean("keFuService");

    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<ChatController2> webSocketSet = new CopyOnWriteArraySet<ChatController2>();
    private static List<String> names= new ArrayList<String>();
    static Map<String, Session> map = new HashMap<String, Session>();   //将联系人通道和联系人同时保存
    private Session session; //会话的session
    private String name; //用户id
    static String type = ""; //用户类型
    
	/**
     * 建立会话
     * @param session  可选的参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private static boolean count = false;
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
      /*  webSocketSet.add(this);     //加入set中
*/        addOnlineCount();           //在线数加1
        if(webSocketSet.size() <= 0) {
        	webSocketSet.add(this);
        }
        this.name= session.getRequestParameterMap().get("name").get(0);//当前会话用户的id
        for (ChatController2 item : webSocketSet) {
        	if(item.name.equals(this.name)) {
        		count = false;
        		break;
        	}else {
        		/**
        		 * 当if没有匹配上他就会走else 然后一直为true 走到结束还是为true 如果中途有一个匹配上了，就证明有这个用户的存在，那么结束循环，边成false 下面则不添加这个用户，
        		 */
        		count = true;
        	}
		}
        if(count) {
        	webSocketSet.add(this); 
        }
        names.add(this.name);//将本次登录用户的姓名添加到names里面
        map.put(name, session);
    }
     
    /**
     * 进行会话消息传递
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    
    @OnMessage
    public void onMessage(String message, Session session,HttpServletRequest request) {
    	String messages[]= message.split("k45jk459fgjdf986kjh98fgdkj3i45y89fdh4598hp90u");
    	String sendName = messages[0];
		String toName = messages[1];
		String sendMessage = messages[2];
		System.err.println("发送消息的id: " + sendName + "  接受消息的id: " + toName +"  发送的内容: " + sendMessage);
    	//聊天会话
		for (ChatController2 item : webSocketSet) {
			//群聊
			if ("所有人".equals(toName)) {
				try {
					item.sendMessage(messages[2]);
				} catch (IOException e) {
					e.printStackTrace();
					continue;
				}
			} else {
				//私聊
				//System.out.println( "发送的用户id: "+sendName+ "  接收的用户id: "+toName+"  socket的用户id： "+item.name);
				if (toName.equals(item.name)) { 
					try {
						/** 保存客服咨询聊天记录 */
						KeFuChat chat = new KeFuChat();
						if(sendName.contains("kefu")) {
							String tString = sendName; 
							tString = tString.replace("kefu", "");
							chat.setKefu_id(Integer.parseInt(tString));
							chat.setUser_id(Integer.parseInt(toName));
							chat.setContent(sendMessage);
							chat.setSender(0);		
							keFuService.saveChatRecord(chat);
						}
						if(toName.contains("kefu")&&toName.length()>4) {
							String tString = toName;
							tString = tString.replace("kefu", "");
							chat.setUser_id(Integer.parseInt(sendName));
							chat.setKefu_id(Integer.parseInt(tString));
							chat.setContent(sendMessage);
							chat.setSender(1);	
							keFuService.saveChatRecord(chat);
						}
						item.sendMessage(sendName+"k45jk459fgjdf986kjh98fgdkj3i45y89fdh4598hp90u"+messages[2]);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
    }
    
    /**
     * 关闭会话
     */
    
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);  //从set中删除
        map.remove(this.name);
        subOnlineCount();           //在线数减1    
        //System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }
     
    /**
     * 会话异常
     * @param session
     * @param error
     */
    
    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }
    
    /**
     * 这个方法与上面几个方法不一样。没有用注解，是根据自己需要添加的方法。
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException{
    	this.session.getBasicRemote().sendText(message);
    }
    
    public void sendMessageToPeople(String toName,String fromName,String message) throws IOException {
    	this.session.getBasicRemote().sendText(toName+fromName+message);
	}
    
    
    /**
     * 当前会话人数
     * @return
     */
    
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
 
    public static synchronized void addOnlineCount() {
        ChatController2.onlineCount++;
    }
     
    public static synchronized void subOnlineCount() {
        ChatController2.onlineCount--;
    }
}